<template>
  <div class="flexContent1">
    <!-- <div class="form"> -->
    <el-form ref="shopForm" :rules="shopRules" :disabled="routerType === 'detail'" :model="shopForm"
      class="demo-form-inline form" label-position="right" label-width="140px">
      <div class="top">

        <div class="basic">基本信息</div>
        <el-row :gutter="24" type="flex">
          <el-col :span="8">
            <el-form-item label="门店名称" prop="name">
              <el-input v-clearEmoji v-model.trim="shopForm.name" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="赠送通证数量" prop="tokenNum">
              <el-input v-clearEmoji :disabled="routerType !== 'add'" v-model.number="shopForm.tokenNum"
                style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="修改期初库存" prop="initialState">
              <el-switch v-model="shopForm.initialState" active-color="#13ce66" active-value="0" inactive-value="1"
                inactive-color="#ccc"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="8">
            <el-form-item prop="region" label="省市区域">
              <el-cascader ref="cascaderAddr" v-model="shopForm.selectedOptions" style="width: 100%" :options="options"
                placeholder="请选择地区" filterable expand-trigger="hover" @change="handleChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店详细地址" prop="address">
              <el-input v-clearEmoji id="tipinput" v-model.trim="shopForm.address" clearable style="width: 100%"
                placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="area" label="门店面积(m²)">
              <el-input v-clearEmoji v-model.trim="shopForm.area" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">

          <el-col :span="8">
            <el-form-item label="门店商圈" prop="businessDistrict">
              <el-select v-model="shopForm.businessDistrict" popper-class="eloption" style="width: 100%">
                <el-option v-for="(val, key) in businessList" :key="key" :value="key" :label="val" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店联系人" prop="storeUser">
              <el-input v-clearEmoji v-model.trim="shopForm.storeUser" style="width: 100%"
                :placeholder="routerType === 'detail' ? '' : '请输入...'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系手机号" prop="storePhone">
              <el-input v-clearEmoji v-model.trim="shopForm.storePhone" style="width: 100%"
                :placeholder="routerType === 'detail' ? '' : '请输入...'" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="center" v-if="!shopId || routerType == 'detail'">

        <div class="basic">
          账户信息
        </div>
        <el-row :gutter="24" type="flex" v-if="!shopId || routerType == 'detail'">
          <el-col :span="8">
            <el-form-item label="账号" prop="userName">
              <el-input v-clearEmoji v-model.trim="shopForm.userName" style="width: 100%" placeholder="请输入门店账号(手机号)" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-clearEmoji v-model.trim="shopForm.password" style="width: 100%" placeholder="请输入..."
                type="password" show-password />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="btm">
        <div class="basic">经营信息</div>
        <el-row :gutter="24" type="flex">
          <el-col :span="8">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-clearEmoji v-model.trim="shopForm.creditCode" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商户号" prop="merchantId">
              <el-input v-clearEmoji v-model.trim="shopForm.merchantId" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分账比例" prop="ratio">
              <el-input v-clearEmoji v-model.trim="shopForm.ratio" style="width: 100%" placeholder="请输入..." />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="8">
            <el-form-item label="门店状态">
              <el-radio-group v-model="shopForm.storeState" size="small">
                <el-radio label="0">启用</el-radio>
                <el-radio label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人名称" prop="legalName">
              <el-input v-clearEmoji v-model.trim="shopForm.legalName" style="width: 100%"
                :placeholder="routerType === 'detail' ? '' : '请输入...'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人手机号" prop="legalPhone">
              <el-input v-clearEmoji v-model.trim="shopForm.legalPhone" style="width: 100%"
                :placeholder="routerType === 'detail' ? '' : '请输入...'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :span="8">
            <el-form-item label="地图坐标" prop="latitude">
              <div class="map">
                <MapContain ref="mapRef" :input-str.sync="shopForm.address" :latitude.sync="latitude"
                  :longitude.sync="longitude" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照" prop="imgUrl">
              <!-- <el-col :span="6"> -->
              <el-upload v-if="!shopForm.imgUrl" name="multipartFile" :limit="1" :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload" list-type="picture-card" :action="action" :data="upData"
                :headers="headers" :on-error="fileUploadError" class="imgUpload">
                <i size="12" class="el-icon-plus" />
                <br />
                <span class="txt">上传</span>
              </el-upload>
              <template v-if="shopForm.imgUrl">
                <div style="display: flex; width: 100%">
                  <!-- <img v-if="shopForm.imgUrl" :src="shopForm.imgUrl"
                      style="height: 50px;object-fit: cover;border: 1px solid #ccc;" alt="" /> -->
                  <el-image v-if="shopForm.imgUrl" style="height: 128px;object-fit: cover;border: 1px solid #ccc;"
                    :src="shopForm.imgUrl" :preview-src-list="[shopForm.imgUrl]" />
                  <div v-if="routerType !== 'detail'" style="
												width: 50px;
                        height: 50px;
												border-radius: 5px;
												border: 1px dashed #ccc;
												text-align: center;
												color: #ccc;
												margin-left: 5px;
											">
                    <i style="cursor: pointer" class="el-icon-delete" @click="delImg" />
                  </div>
                </div>
              </template>
              <!-- </el-col> -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分录日期" prop="entriesDays">
              <el-checkbox-group v-model="shopForm.entriesDays" size="mini" style="width:80%">
                <el-checkbox-button v-for="item in dateList" :key="item.key" :label="item.key">
                  {{ item.value }}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="btnDiv">
          <el-button v-if="routerType === 'add' || routerType === ''" class="submitBtn" style="width: 88px;"
            @click.stop="addShop">
            确定
          </el-button>
          <el-button v-if="routerType === 'edit'" class="submitBtn" style="width: 88px;" @click.stop="updateShop">
            提交
          </el-button>
          <el-form v-if="routerType === 'detail'">
            <el-form-item>
              <el-button v-if="routerType === 'detail'" class="celBtn" style="width: 88px;" @click.stop="returnBtn">
                返回
              </el-button>
            </el-form-item>
          </el-form>
          <el-button v-if="routerType !== 'detail'" class="celBtn" style="width: 88px;" @click.stop="cancelBtn">
            取消
          </el-button>
        </div>
      </div>
    </el-form>
    <!-- </div> -->
  </div>
</template>

<script>
import MapContain from '@/components/MapContain';
import { regionData, CodeToText } from 'element-china-area-data';
import { addShop, getShopDetail, updateShopDetail } from '@/api/shop';
import { getToken } from '@/utils/auth';
import { getDictValueAndNameSource } from '@/api/dictionary';
export default {
  name: 'GoodsAdd',
  components: {
    MapContain
  },
  data() {
    return {
      latitude: 34.75,
      longitude: 113.616029,
      headers: { token: getToken() },
      action: process.env.VUE_APP_UPLOAD_BASE_API + '/file/uploadFile',
      upData: {
        fileType: '0'
      },
      routerType: 'add',
      options: regionData,
      selectedOptions: [],
      selectedOptionsForm: {
        province: '',
        county: '',
        area: ''
      },
      addtions: {
        names: ''
      },
      businessList: {},
      shopForm: {
        selectedOptions: [],
        name: '', // 门店名称
        storeUser: '', // 联系人
        storePhone: '', // 联系人手机号
        region: '', // 省市区域
        address: '', // 详细地址
        userName: '', // 账号
        password: '', // 密码
        creditCode: '', // 统一社会信用代码
        legalName: '', // 法人名称
        imgUrl: '', // 营业执照地址
        legalPhone: '', // 法人手机号
        longitude: null, // 经度
        latitude: null, // 纬度
        storeState: '0', // 门店状态：0.启用，1.禁用
        entriesDays: [],
        merchantId: '', // 商户号
        area: '', // 门店面积
        tokenNum: '', // 赠送通证
        businessDistrict: '', // 门店商圈
        initialState: '0', // 初期库存
        ratio: ''   // 分账比例
      },
      shopRules: {
        area: [
          {
            required: true,
            message: '请输入门店面积',
            trigger: 'blur'
          },
          {
            pattern: /^\d+$/,
            message: '门店面积只能输入数字',
            trigger: 'blur'
          }
        ],
        tokenNum: [
          {
            required: true,
            message: '请输入赠送通证数量',
            trigger: 'blur'
          },
          {
            pattern: /^\d+$/,
            message: '请输入数字',
            trigger: 'blur'
          }
        ],
        businessDistrict: [
          {
            required: true,
            message: '请选择门店商圈',
            trigger: 'blur'
          }
        ],
        latitude: [
          {
            required: true,
            message: '请选择地图坐标',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入门店名称',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 15,
            message: '门店名称长度不能超过15个字符',
            trigger: 'blur'
          }
        ],
        storeUser: [
          {
            min: 0,
            max: 10,
            message: '联系人名称不能超过10个字符',
            trigger: 'blur'
          },
          {
            pattern:
              /^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/,
            message: '联系人只能输入汉字',
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入门店地址',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 30,
            message: '门店地址不能超过30个字符',
            trigger: 'blur'
          }
        ],
        userName: [
          {
            required: true,
            message: '请输入门店账号',
            trigger: 'blur'
          },
          {
            pattern:
              /^1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            pattern: /^([a-zA-Z0-9])+$/,
            message: '支持数字、大写英文字母',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 15,
            message: '密码不能超过15个字符',
            trigger: 'blur'
          }
        ],
        creditCode: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          },
          {
            pattern: /^([A-Z0-9])+$/,
            message: '支持数字、大写英文字母',
            trigger: 'blur'
          }
        ],
        legalName: [
          {
            min: 0,
            max: 10,
            message: '法人名称不能超过10个字符',
            trigger: 'blur'
          },
          {
            pattern: /^([\u4e00-\u9fa5])+$/,
            message: '只能输入中文',
            trigger: 'blur'
          }
        ],
        legalPhone: [
          {
            pattern:
              /^1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        storePhone: [
          {
            pattern:
              /^1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        imgUrl: [
          {
            required: true,
            message: '请上传营业执照',
            trigger: 'blur'
          }
        ],
        region: [
          {
            required: true,
            message: '请选择区域',
            trigger: 'blur'
          }
        ],
        entriesDays: [
          {
            required: true,
            message: '请选择分录日期',
            trigger: 'blur'
          }
        ],
        merchantId: [
          {
            required: true,
            message: '请输入门店商户号',
            trigger: 'blur'
          },
          {
            pattern: /^([0-9])+$/,
            message: '只能输入数字',
            trigger: 'blur'
          }
        ],
        ratio: [
          {
            required: true,
            message: '请输入分账比例',
            trigger: 'blur'
          },
          {
            pattern: /^(?!(^0$|0\.0{1,2}$))[0-9]+(\.[0-9]{1,2})?$/,
            message: '只能输入数字支持两位小数',
            trigger: 'blur'
          }
        ]
      },
      shopId: '',
      roleList: [],
      dateList: []
    };
  },
  watch: {
    shopForm: {
      handler(newVal, oldVal) {
        if (newVal.longitude) {
          this.shopForm.longitude = Number(newVal.longitude);
          // this.longitude = Number(newVal.longitude)
        }
        if (newVal.latitude) {
          this.shopForm.latitude = Number(newVal.latitude);
          this.latitude = Number(newVal.latitude);
        }
      },
      deep: true,
      immediate: true
    },
    latitude: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.shopForm.latitude = Number(newVal);
        }
      },
      deep: true,
      immediate: true
    },
    longitude: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.shopForm.longitude = Number(newVal);
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDateList();
    this.getBusinessList();
    this.routerType = this.$route.query.type
      ? this.$route.query.type
      : 'add';
    this.shopId = this.$route.query?.id;
    if (this.shopId) {
      this.getShopDetail();
    }
  },
  methods: {
    async getShopDetail() {
      const res = await getShopDetail({ id: this.shopId });
      console.log(res);
      if (res.code === 200) {
        const data = res.data;
        this.shopForm = data.store;
        this.longitude = Number(data.store.longitude);
        this.latitude = Number(data.store.latitude);
        this.$set(
          this.shopForm,
          'merchantId',
          String(data.store.merchantId ? data.store.merchantId : '')
        );
        this.$set(
          this.shopForm,
          'tokenNum',
          String(data.store.tokenNum ? data.store.tokenNum : '0')
        );
        this.$set(
          this.shopForm,
          'ratio',
          String(data.store.ratio ? data.store.ratio : '0')
        );
        this.shopForm.password = this.shopForm.password.substring(
          0,
          15
        );
        this.$nextTick(() => {
          this.$refs.mapRef.initMap();
        });
        // this.shopForm.selectedOptions = data.store.selectedOptionsId.split(',')
        console.log('门店', this.shopForm);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getDateList() {
      const res = await getDictValueAndNameSource('DATE');
      if (res.code === 200) {
        for (const item in res.data) {
          this.dateList.push({ key: item, value: res.data[item] });
        }
        // console.log(res.data, 'dateList')
      }
    },
    // 获取商圈
    async getBusinessList() {
      const res = await getDictValueAndNameSource('STORE_BUSINESS_AREA');
      if (res.code === 200) {
        // for (const item in res.data) {
        this.businessList = res.data;
        //
        // }
      }
    },
    // 获取省市区
    handleChange(value) {
      this.shopForm.selectedOptions = value;
      console.log(this.shopForm.selectedOptions);
      var name = '';
      this.shopForm.selectedOptions.map(item => {
        name += CodeToText[item] + '/';
      }); // 将省市区三个拼接一起
      this.addtions.names = name;
      console.log(this.addtions.names); // 运用了CodeToText把编码转成了中文
      this.selectedOptionsForm.province =
        CodeToText[this.selectedOptions[0]];
      this.selectedOptionsForm.county =
        CodeToText[this.selectedOptions[1]];
      this.selectedOptionsForm.area = CodeToText[this.selectedOptions[2]];

      console.log(this.selectedOptionsForm);
      this.shopForm.region = this.addtions.names;
    },
    handleAvatarSuccess(res, file) {
      this.shopForm.imgUrl =
        this.$store.getters.imgBaseUrl +
        res.data.filePath +
        res.data.fileNewName;
      console.log(res);
      this.$message.success(res.message);
    },
    beforeAvatarUpload(file) {
      // console.log('before', file)
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.'));
      const isOKType =
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg';
      if (!isOKType) {
        this.$message.error('图片格式只能为jpeg/png/jpg');
      }

      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isLt2M && isOKType;
    },
    fileUploadError(res) {
      this.$message.error(res.message);
    },
    delImg() {
      this.shopForm.imgUrl = '';
    },
    addShop() {
      console.log(this.shopForm);
      this.$refs.shopForm.validate(async isOk => {
        // console.log(this.shopForm, 'form')
        if (isOk) {
          const res = await addShop(this.shopForm);
          console.log(res.code);
          if (res.code === 200) {
            this.$message.success('添加成功');
            this.$refs.shopForm.resetFields();
            this.closeTag('shopInfo');
          } else {
            // this.$message.error(res.message);
          }
        } else {
          this.$message.warning('请检查填写的信息');
        }
      });
    },
    updateShop() {
      console.log(this.shopForm);
      this.$refs.shopForm.validate(async isOk => {
        if (isOk) {
          const res = await updateShopDetail({
            ...this.shopForm,
            id: this.shopId
          });
          console.log(res.code);
          if (res.code === 200) {
            this.$message.success('修改成功');
            this.$refs.shopForm.resetFields();
            this.$router.push('shopInfo');
          } else {
            // this.$message.error(res.message);
          }
        } else {
          this.$message.warning('请检查填写的信息');
        }
      });
    },
    returnBtn() {
      this.closeTag('shopInfo');
    },
    cancelBtn() {
      this.closeTag('shopInfo');
    }
  }
};
</script>

<style lang="scss" scoped>
.flexContent1 {
  height: 100%;
  background-color: #EEEEEE;

  .form {
    height: 100%;
    // background-color: #fff;
    // padding: 32px;
    display: flex;
    flex-direction: column;

    .top {
      // width: 100%;
      background-color: #fff;
      padding: 32px 32px 0 32px;
      border-radius: 6px 6px 6px 6px;
      // height: 438px;
      margin-bottom: 16px;
    }

    .center {
      // width: 100%;
      background-color: #fff;
      padding: 32px 32px 0 32px;
      border-radius: 6px 6px 6px 6px;
      // height: 438px;
      margin-bottom: 16px;
    }

    .btm {
      // width: 100%;
      background-color: #fff;
      padding: 32px 32px 0 32px;
      border-radius: 6px 6px 6px 6px;
    }

    .btnDiv {
      display: flex;
      // text-align: right;
      padding-left: 90%;

    }

    .basic {
      font-family: PingFang SC, PingFang SC;
      font-size: 20px;
      color: rgba(0, 0, 0, 0.9);
      margin-bottom: 32px;
    }

    .imgUpload {
      ::v-deep .el-upload:hover {
        border-color: #409eff;
      }

      ::v-deep .el-upload {
        position: relative;
        margin-bottom: 10px;
        margin-left: 5px;
        width: 120px;
        height: 128px;
        line-height: 20px;
        padding-top: 35px;
      }

      .txt {
        color: #595858;
        font-size: 12px;
      }
    }
  }
}

.el-upload--picture-card i {
  font-size: 12px !important;
}

.el-button--small {
  padding: 9px 0;
}

::deep el-button {
  text-align: center;
}

.map {
  width: 300px;
  height: 128px;
}
</style>
<style>
.el-checkbox-button {
  margin-right: 5px;
  /* border: none !important; */
}

.el-checkbox-button__inner {
  border: 1px solid #dcdfe6 !important;
  border-radius: 5px !important;
  box-shadow: none !important;
}
.el-icon-circle-close:before {
  color: #fff !important;
}
</style>
